<template>
  <t-dialog v-model:visible="model" :header="dialogTitle" :confirm-loading="confirmPending" confirm-btn="确定" @confirm="handleConfirm">
    <t-form ref="dialogForm" :data="formData" :rules="formRules">
      <t-form-item label="内容名称" name="contentName">
        <t-input v-model="formData.contentName" placeholder="请输入内容名称" />
      </t-form-item>
      <t-form-item label="启用" name="enabled">
        <t-switch v-model="formData.enabled" :custom-value="[EnabledStatus.ENABLED, EnabledStatus.DISABLED]" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import type { FormInstanceFunctions, FormRules } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { computed, reactive, ref, useTemplateRef, watchEffect } from 'vue'

import { EnabledStatus } from '@/api/model/common'
import type { TicketContentReqData } from '@/api/model/ticket'
import { createTicketContent, updateTicketContent } from '@/api/ticket'

export type TicketConentFormDialogData = TicketContentReqData

const props = defineProps<{ id?: string, data: TicketConentFormDialogData }>()
const emits = defineEmits<{
  (e: 'success'): void
}>()
const isEditModel = computed(() => !!props.id)
const dialogTitle = computed(() => (isEditModel.value ? '编辑内容' : '添加内容'))
const model = defineModel<boolean, 'visible'>('visible')
const formData = reactive<TicketContentReqData>(
  {
    contentName: props.data.contentName,
    enabled: props.data.enabled,
  }
)
watchEffect(() => {
  Object.assign(formData, props.data)
})
const formRules: FormRules<TicketContentReqData> = {
  contentName: [{ required: true, message: '请输入内容名称', type: 'error' }],
  enabled: [{ required: true, message: '请选择状态', type: 'error' }],
}
const dialogForm = useTemplateRef<FormInstanceFunctions<typeof formData>>('dialogForm')
const confirmPending = ref(false)
function handleConfirm() {
  dialogForm.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      confirmPending.value = true
      if (isEditModel.value) {
        updateTicketContent({ id: props.id!, ...formData }).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('更新成功')
          emits('success')
        })
      }
      else {
        createTicketContent(formData).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('创建成功')
          emits('success')
        })
      }
    }
  })
}
</script>
<style scoped>

</style>
